//@ sourceURL=lims-equipt-serial-listener.js
coreEquiptAcqConfig.serialListener = Gikam.extend(coreEquiptAcqConfig.serialListener, {
    connect : function(showTag, reConnect) {
        var _this = this;
        var def = Gikam.getDeferred();
/*        if (Gikam.isEmpty(reConnect) || Gikam.isTrue(reConnect)) {
            _this.disconnectIfConnected();
        }
        var url = 'http://localhost:9778/ws';
        if (_this.equipt.acqCategory == 'net') {
            url = IFM_CONTEXT + '/ws';
        }
        _this.client = Stomp.over(new SockJS(url));
        _this.client.connect({}, function(frame) {
            console.info(Gikam.propI18N('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.CONNECT_SUCCESS'));
            _this.updateConnectionStatus();
            if (!Gikam.isFalse(showTag)) {
                Gikam.toast('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.CONNECT_SUCCESS', 3, 'top');
            }
            _this.subscribe();
            def.resolve();
        }, function(error) {
            _this.equipt = null;
            Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.CONNECT_FAILURE');
            _this.disconnectIfConnected();
            _this.updateConnectionStatus();
        });*/
        console.info(Gikam.propI18N('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.CONNECT_SUCCESS'));
        _this.updateConnectionStatus();
        if (!Gikam.isFalse(showTag)) {
            Gikam.toast('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.CONNECT_SUCCESS', 3, 'top');
        }
        def.resolve();
        return def;
    },

    open : function(acqCategory, equipt, action, param, showTag) {
        var _this = this;
        var def = Gikam.getDeferred();
        Gikam.getLastModal() && Gikam.getLastModal().window.showMask();
        if (acqCategory === 'serial' && Gikam.isEmpty(equipt.ext$.moduleipport)) {// 串口连接 并且不需要到中间采集模块处理
            var url = 'http://localhost:9778/serial-ports/' + equipt.com + '/open';
            Gikam.postSync(url, JSON.stringify(param)).done(function(result) {
                if (!result) {
                    Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.CONNECT_FAILURE');
                    return;
                }

                _this.equipt = equipt;
                var connectDef = _this.connect(showTag);

                _this.action = action + '(response.body, getedValue, equipt)';

                def.resolve(connectDef);

            }).fail(function() {

            }).always(function() {
                var lastModal = Gikam.getLastModal();
                lastModal && lastModal.window.closeMask();
            });

        } else {// 网口连接 ||中间采集模块形式
            var url = coreEquiptAcqConfig.baseUrl + '/' + equipt.id + '/action/connect';
            Gikam.put(url, param).done(function(result) {
                if (result === 'fail') {
                    Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.CONNECT_FAILURE');
                } else {

                    _this.equipt = equipt;
                    var connectDef = _this.connect(showTag);

                    _this.action = action;

                    def.resolve(connectDef);
                }
            }).fail(function(info) {
                console.debug("fail:"+info);
                Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.CONNECT_FAILURE');
            }).always(function() {
                var lastModal = Gikam.getLastModal();
                lastModal && lastModal.window.closeMask();
            })
        }

        return def;
    },

    // 监听
    subscribe : function() {
        var _this = this;

        if (_this.isConnected()) {

            var topic = '/topic/tcp-ports/' + _this.equipt.id;

            if (Gikam.isNotEmpty(_this.equipt.ext$.moduleipport)) {
                topic = '/topic/equipt/'+ _this.equipt.id
            } else {
                if (_this.equipt.acqCategory == 'serial') {
                    topic = '/topic/serial-ports';
                }
            }
            _this.subscription = _this.client.subscribe(topic, function(response) {
                /* 对仪器采集数据处理 1,配置了开始标记/结束标记 2,退而取这个方案 脚本解析 */
                var equipt = _this.equipt;
                _this.callback(response, response.body, equipt);

            });
            console.debug('websocket listen success');
        }
    },
    callback : function(response, responseData, equipt) {
        var _this = this;
        if (Gikam.isFunction(_this.action)) {
            _this.action.call(null, response, responseData, equipt);
        }

    },
    tag : 0,
    /**
     * 弹出采集页面
     * @param equiptIdList 设备编号
     * @param saveDataCallBack 点击保存时的回调
     */
    showAnalysisModal : function (equiptIdList, saveDataCallBack, sampleNo) {
        var _this = this;
        // 1.获取设备采集信息
        _this.tag = 0;
        _this.sampleNo = sampleNo;
        if (Gikam.isEmpty(equiptIdList)) {
            Gikam.alert('BASEMODULE.BUSINESS.TEST_MATRIX.TIP.NO_EQUIPT');
            return;
        }
        var equiptList;
        workspace.window.showMask();
        Gikam.postSync(coreEquiptAcqConfig.equiptUrl + '/queries', Gikam.getJsonWrapper({
            f : {
                id_IN : equiptIdList.join(',')
            }
        })).done(function(pageData) {
            if (Gikam.isNotEmpty(pageData) && Gikam.isNotEmpty(pageData.rows)) {
                equiptList = pageData.rows;
            }
        }).always(function() {
            workspace.window.closeMask();
        });

        if (Gikam.isEmpty(equiptList)) {
            Gikam.alert('BASEMODULE.BUSINESS.TEST_MATRIX.TIP.NO_EQUIPT');
            return;
        }
        var keyFunction = function(event) {
            var keyCode = event.keyCode;
            // B建、Enter（控制键）、Enter（小键盘）
            if (keyCode === 66 || keyCode === 13 || keyCode === 108) {
                if (_this.tag === 0) {
                    _this.tag += 1;
                    setTimeout(function() {
                        if (_this.tag === 1) {
                            _this.sendMessage();
                        }
                        _this.tag = 0;
                    }, 2000);
                } else {
                    _this.tag += 1;
                    _this.confirmAcq(saveDataCallBack);
                }
            }
        };

        window.addEventListener('keydown', keyFunction, false)

        var simpleModal = Gikam.createSimpleModal({
            title : 'BASEMODULE.BUSINESS.ZRTC.SAMPLE-TASKS.MODAL.EQUIPT-ACQ',
            width : 1000,
            height : 500,
            showMaxBtn : false,
            bodyStyle : {
                padding : "0 16px"
            },
            toolbarFormatter : function () {
                return [];
            },
            onBeforeClose : function() {
                window.removeEventListener('keydown', keyFunction, false)
            },
            onAfterClose : function() {
                console.info('close connect...');
                _this.disconnectIfConnected();
            }
        });

        var grid = Gikam.create('grid', {
            id : _this.idManager.limsEquiptAcqResultGrid,
            fill : true,
            autoSave : false,
            page : false,
            toolbar : _this.getAcqGridToolbar(equiptList, saveDataCallBack),
            columns : coreEquiptAcqConfig.getAcqAnalysisResultColumns(),
            renderTo : simpleModal.layout.options.center.$dom
        });
    },

    getAcqGridToolbar : function (equiptList, saveDataCallBack) {
        var _this = this;
        var equiptItemList = equiptList.map(function (equipt) {
            return {
                value : equipt.id,
                text : equipt.equiptName
            }
        });
        var instList = _this.getIntSelectItemList(equiptList[0].id);
        var value;
        var instItems;
        if (Gikam.isEmpty(instList)) {
            value = null;
            instItems = [];
        } else {
            Gikam.each(instList, function (index, item) {
                item.value = item.id;
                item.text = item.instructionName;
            });
            instItems = instList;
            value = instList[0].value;
        }

        return [{
            type : 'form',
            refreshGrid : false,
            id : _this.idManager.equiptAcqSampleIncForm,
            titleWidthAuto : true,
            fields : [{
                field : 'incType',
                title : 'T_CORE_FILE_ACQ_RESULT.SAMPLENO',
                type : 'select',
                width : 120,
                value : 'increment',
                items : [{
                    value : 'increment',
                    text : '自增'
                }, {
                    value : 'common',
                    text : '相同'
                }],
            }]
        }, {
            type : 'form',
            refreshGrid : false,
            id : _this.idManager.equiptSelectForm,
            titleWidthAuto : true,
            fields : [{
                field : 'equiptId',
                title : 'T_EQUIPT.EQUIPTNAME',
                width : 160,
                type : 'select',
                items : equiptItemList,
                value : equiptItemList[0].value,
                onChange : function (field, value) {
                    var instField = Gikam.getComp(_this.idManager.limsEquiptAcqSendMessageForm).getField('id');
                    var instList = _this.getIntSelectItemList(value);
                    if (Gikam.isEmpty(instList)) {
                        instField.value = null;
                        instField.setItems([]);
                    } else {
                        Gikam.each(instList, function (index, item) {
                            item.value = item.id;
                            item.text = item.instructionName;
                        });
                        instField.setItems(instList);
                        instField.value = instList[0].value;
                    }
                }
            }]
        }, {
            type : 'form',
            id : _this.idManager.limsEquiptAcqSendMessageForm,
            refreshGrid : false,
            titleWidthAuto : true,
            width : 160,
            fields : [{
                field : 'id',
                title : 'T_LIMS_EQUIPT_ACQ_CONFIG_INST.INSTRUCTIONNAME',
                type : 'select',
                value : value,
                items : instItems
            }],
        }, {
            type : 'button',
            text : 'BASELINE.MODULE.COMMON.RESOURCE.EQUIPT.ARCHIVESS.BUTTON.ACQ_CONFIG_SEND_MESSAGE',
            icon : 'submit', color: 'success',
            onClick : function () {
                _this.sendMessage();
            }
        }, {
            type : 'button',
            text : 'GIKAM.BUTTON.DELETE',
            icon : 'remove-row',
            onClick : function () {
                var analysisResultGrid = Gikam.getComp(_this.idManager.limsEquiptAcqResultGrid);
                var selections = analysisResultGrid.getSelections();
                var dataList = analysisResultGrid.getData();
                var remainList = dataList.filter(function(data) {
                    return !selections.some(selectIiem => selectIiem.gridIndex === data.gridIndex);
                });
                analysisResultGrid.refreshByData({
                    rows : remainList
                });
            }
        }, {
            type : 'button',
            text : 'GIKAM.BUTTON.CONFIRM',
            icon : 'select',
            onClick : function () {
                _this.confirmAcq(saveDataCallBack);
            }
        }]
    },

    confirmAcq : function(saveDataCallBack) {
        var _this = this;
        var acqDataList = Gikam.getComp(_this.idManager.limsEquiptAcqResultGrid).getData();
        saveDataCallBack && saveDataCallBack(acqDataList);
        // Gikam.getLastModal() && Gikam.getLastModal().close();
    },

    getIntSelectItemList : function (equiptId) {
        var _this = this;
        var itemList = [];
        Gikam.getJsonSync(Gikam.select.getConfigParam('equipt-acq-instruction').url + Gikam.param({
            acqConfigId : equiptId,
            instructionType_EQ : 'result'
        })).done(function (instList) {
            if (Gikam.isNotEmpty(instList)) {
                Gikam.each(instList, function (index, item) {
                    item.value = item.id;
                    item.text = item.instructionName;
                });
                itemList = instList;
            }

        });
        return itemList;
    },

    sendMessage : function () {
        var _this = this;
        var equiptForm = Gikam.getComp(_this.idManager.equiptSelectForm);
        var config = _this.getAcqConfig(equiptForm.getData().equiptId);
        if (Gikam.isFalse(_this.validateData(config))) {
            return;
        }
        var send = function() {
            var instId = Gikam.getComp(_this.idManager.limsEquiptAcqSendMessageForm).getData().id;
            var items = Gikam.getComp(_this.idManager.limsEquiptAcqSendMessageForm).getField('id').items;
            if (Gikam.isEmpty(instId)) {
                Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.NO_INST');
                return;
            }
            var filterInst = items.filter(function (item) {
                return item.value == instId;
            });
            // 发送指令
            var url = '';
            var messageData = filterInst[0];
            if (Gikam.isNotEmpty(config.ext$.moduleipport)) {
                Gikam.postText(Gikam.printf(coreEquiptAcqConfig.baseUrl + '/{id}/action/test-send', {
                    id : config.id
                }), Gikam.getJsonWrapper(null, ['', [messageData]])).done(function (result) {
                    console.debug('send messge success, {}, {}', config.id, messageData );
                    Gikam.toast('send success');
                });
            } else {
                if (config.acqCategory == 'net') {
                    url = Gikam.printf(coreEquiptAcqConfig.baseUrl + '/{ipPort}/send', {
                        ipPort : config.ip + (config.port ? ':' + config.port : ''),
                    })
                }
                if (config.acqCategory == 'serial') {
                    url = 'http://localhost:9778/serial-ports/' + config.com + '/send';
                }
                Gikam.postText(url, messageData.instruction).done(function (result) {
                    Gikam.toast('send success');
                });
            }
        }
        if (_this.isConnected()) {
            send && send();
        } else {
            _this.sendOpenConnect(config).done(function(connectDef) {
                connectDef.done(function() {
                    send && send();
                })
            });
        }
    },

    getAcqConfig : function (equiptId) {
        var _this = this;
        var acqConfig = {};
        if (equiptId) {
            workspace.window.showMask();
            Gikam.getJsonSync(Gikam.printf(coreEquiptAcqConfig.baseUrl + '/{id}', {
                id : equiptId
            })).done(function (data) {
                acqConfig = data;
            }).always(function () {
                workspace.window.closeMask();
            });
        }
        return acqConfig;
    },

    validateData : function (acqConfigInfo) {
        var _this = this;
        if (Gikam.isEmpty(acqConfigInfo)) {
            Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.NO_CONFIG');
            return;
        }
        if (acqConfigInfo.acqCategory == 'net') {
            if (Gikam.isEmpty(acqConfigInfo.ip) || Gikam.isEmpty(acqConfigInfo.port)) {
                Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.NO_IP_PORT');
                return false;
            }
        } else if (acqConfigInfo.acqCategory == 'serial') {
            if (Gikam.isEmpty(acqConfigInfo.com)) {
                Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.NO_COM');
                return false;
            }

            if (Gikam.isEmpty(acqConfigInfo.baudRate)) {
                Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.NO_BAUDRATE');
                return false;
            }

            if (Gikam.isEmpty(acqConfigInfo.dataBit)) {
                Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.NO_DATABIT');
                return false;
            }

            if (Gikam.isEmpty(acqConfigInfo.stopBit)) {
                Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.NO_STOPBIT');
                return false;
            }

            if (Gikam.isEmpty(acqConfigInfo.parityCheck)) {
                Gikam.alert('CORE.MODULE.EQUIPT.ACQCONFIGS.TIP.NO_PARITYCHECK');
                return false;
            }
        } else {
            return false;
        }
        return true;
    },

    /**
     * 连接
     */
    sendOpenConnect : function (equipt) {
        var _this = this;

        // 获取数据后的操作
        var action = function (response, data, equipt) {
            console.debug(data);
            var analysisResultGrid = Gikam.getComp(_this.idManager.limsEquiptAcqResultGrid);
            var dataArray = analysisResultGrid.getData();
            try {
                var newDataArray = data;
                analysisResultGrid.refreshByData({
                    rows : dataArray.concat(newDataArray)
                });
            } catch (e) {
                Gikam.toast(data, 3, 'top');
            }
        };

        if (equipt.acqCategory == 'net') {
            return coreEquiptAcqConfig.serialListener.open('net', equipt, action, null, false);
        } else if (equipt.acqCategory == 'serial') {
            return coreEquiptAcqConfig.serialListener.open('serial', equipt, action, {
                baudRate : equipt.baudRate,
                dataBits : equipt.dataBit,
                stopBits : equipt.stopBit,
                parity : equipt.parityCheck,
                end : equipt.endFlag
            });
        }
    },

    idManager : {
        limsEquiptAcqResultGrid : 'lims-equipt-acq-config-acq-grid',
        equiptSelectForm : 'lims-equipt-acq-config-acq-connect-equipt-form',
        equiptAcqSampleIncForm : 'lims-equipt-acq-config-acq-connect-sample-inc-form',
        limsEquiptAcqSendMessageForm : 'lims-equipt-acq-config-acq-connect-message-form',
        limsEquiptAcqConfigConnectTestConnectButton : 'lims-equipt-acq-config-connect-button',
        limsEquiptAcqConfigConnectTestDisConnectButton : 'lims-equipt-acq-config-disconnect-button',
        limsEquiptAcqConfigConnectTestSendMessageButton : 'lims-equipt-acq-config-send-message-button',
    },
});